package com.beeantec.jnrerc.modules.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beeantec.jnrerc.core.api.dto.PagingReqDTO;

import com.beeantec.jnrerc.entity.PaperQuAnswer;
import com.beeantec.jnrerc.entity.Qu;
import com.beeantec.jnrerc.modules.paper.service.PaperQuAnswerService;
import com.beeantec.jnrerc.modules.qu.service.QuService;
import com.beeantec.jnrerc.core.utils.UserUtils;
import com.beeantec.jnrerc.dto.MemberWbookDTO;
import com.beeantec.jnrerc.entity.MemberWbook;
import com.beeantec.jnrerc.mapper.MemberWbookMapper;
import com.beeantec.jnrerc.modules.user.service.MemberWbookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
* <p>
* 语言设置 服务实现类
* </p>
*
* @author Anthony
* @since 2020-05-27 17:56
*/
@Service
public class MemberWbookServiceImpl extends ServiceImpl<MemberWbookMapper, MemberWbook> implements MemberWbookService {

    @Autowired
    private QuService quService;

    @Autowired
    private PaperQuAnswerService paperQuAnswerService;

    @Override
    public IPage<MemberWbookDTO> paging(PagingReqDTO<MemberWbookDTO> reqDTO) {

        //创建分页对象
        Page query = new Page<>(reqDTO.getCurrent(), reqDTO.getSize());

        //查询条件
        QueryWrapper<MemberWbook> wrapper = new QueryWrapper<>();
        // 查找用户的错题
        wrapper.lambda().eq(MemberWbook::getUserId, reqDTO.getUserId());

        MemberWbookDTO params = reqDTO.getParams();
        if(params!=null){
            if(!StringUtils.isEmpty(params.getTitle())){
                wrapper.lambda().like(MemberWbook::getTitle, params.getTitle());
            }

            if(!StringUtils.isEmpty(params.getExamId())){
                wrapper.lambda().eq(MemberWbook::getExamId, params.getExamId());
            }
        }

        //获得数据
        IPage<MemberWbook> page = this.page(query, wrapper);
        //转换结果
        IPage<MemberWbookDTO> pageData = JSON.parseObject(JSON.toJSONString(page), new TypeReference<Page<MemberWbookDTO>>(){});
        return pageData;
     }



    @Override
    public void addBook(String examId, String quId,Integer paperId,String userId) {

        QueryWrapper<MemberWbook> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(MemberWbook::getUserId, userId)
                .eq(MemberWbook::getExamId, examId)
                .eq(MemberWbook::getQuId, quId);

        //查找已有的错题信息
        MemberWbook book = this.getOne(wrapper, false);


        // 问题
        Qu qu = quService.getById(quId);

        if (book == null) {
            book = new MemberWbook();
            book.setExamId(examId);
            book.setUserId(userId);
            book.setTitle(qu.getContent());
            book.setQuId(quId);
            book.setPaperId(paperId);
            book.setWrongCount(1);
            Integer maxSort = this.findMaxSort(examId, userId);
            book.setSort(maxSort+1);

            this.save(book);
        } else {
            book.setWrongCount(book.getWrongCount()+1);
            this.updateById(book);
        }
    }

    @Override
    public String findNext(String examId, String quId,String userId) {


        Integer sort = 999999;

        if(!StringUtils.isEmpty(quId)){
            QueryWrapper<MemberWbook> wrapper = new QueryWrapper<>();
            wrapper.lambda()
                    .eq(MemberWbook::getUserId, userId)
                    .eq(MemberWbook::getExamId, examId)
                    .eq(MemberWbook::getQuId, quId);
            wrapper.last(" ORDER BY `sort` DESC");

            MemberWbook last = this.getOne(wrapper, false);
            if(last!=null){
                sort = last.getSort();
            }
        }

        QueryWrapper<MemberWbook> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(MemberWbook::getUserId, userId)
                .eq(MemberWbook::getExamId, examId)
                .lt(MemberWbook::getSort, sort);
        wrapper.last(" ORDER BY `sort` DESC");

        MemberWbook next = this.getOne(wrapper, false);
        if(next != null){
            return next.getQuId();
        }

        return null;
    }



    @Override
    public List<PaperQuAnswer>  findPaperError(String examId, Integer paperId,String userId) {


        Integer sort = 999999;
        List<MemberWbook> wbooks = new ArrayList<>();
        List<String> wbookIds = new ArrayList<>();
        List<PaperQuAnswer> paperQuAnswerList = new ArrayList<>();
        if(!StringUtils.isEmpty(paperId)){
            QueryWrapper<MemberWbook> wrapper = new QueryWrapper<>();
            wrapper.lambda()
                    .eq(MemberWbook::getUserId, userId)
                    .eq(MemberWbook::getExamId, examId)
                    .eq(MemberWbook::getPaperId, paperId)
                    .orderByDesc(MemberWbook::getUpdateTime);

            wbooks = baseMapper.selectList(wrapper);
        }
        for (MemberWbook memberWbook:wbooks){
            wbookIds.add(memberWbook.getQuId());
        }
        QueryWrapper<PaperQuAnswer> quAnswerQueryWrapper = new QueryWrapper<>();
        quAnswerQueryWrapper.lambda().eq(PaperQuAnswer::getPaperId,paperId.toString()).in(PaperQuAnswer::getQuId,wbookIds);
        paperQuAnswerList= paperQuAnswerService.list(quAnswerQueryWrapper);

        return paperQuAnswerList;
    }




    /**
     * 查找最大的排序
     * @param userId
     * @return
     */
    private Integer findMaxSort(String examId, String userId){

        QueryWrapper<MemberWbook> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(MemberWbook::getExamId, examId)
                .eq(MemberWbook::getUserId, userId);
        wrapper.last(" ORDER BY `sort` DESC");

        MemberWbook book = this.getOne(wrapper, false);
        if(book == null){
            return 0;
        }
        return book.getSort();
    }


}
